Skip to main content

20240619 2288 - Medium - array

2288. Apply Discount to Prices

class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
def getPriceAfterDiscount(num):
return str(print("%.2f" % (num * (discount / 100))))
def isDigit(c):
return ord("0") < ord(c) < ord("9")
res = ""
i = 0
while i < len(sentence):
if sentence[i] == "$":
res += sentence[i]
tmpi = i
i += 1
valid = True
num = 0
ni = 10
while i < len(sentence):
if isDigit(sentence[i]):
# print(num, ni, int(sentence[i]))
num = num * ni + int(sentence[i])
i += 1
elif sentence[i] == " ":
valid = True
i += 1
break
else:
valid = False
i += 1
while i < len(sentence) and sentence[i] != " ":
i += 1
break

if valid and tmpi + 1 != i:
res += getPriceAfterDiscount(num) + " "
print(num)
else:
res += sentence[i]
# space or lowercase character
i += 1
return res

solution

  • split sentence by space
  • find the "$" and then the digit
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
d = 1 - discount / 100
a = sentence.split(' ')
for i, w in enumerate(a):
if w[0] == '$' and w[1:].isdigit():
a[i] = f"${int(w[1:]) * d :.2f}"
return ' '.join(a)